#include<iostream>
#include<unistd.h>
#include<pthread.h>

using namespace std;

int tickets = 10000;

pthread_mutex_t mymutex;

// 抢票
void *function(void *argc)
{
    while (true)
    {
        pthread_mutex_lock(&mymutex);
        if (tickets > 0)
        {
            usleep(3000);
            cout << (char *)argc << " ticket:" << tickets << endl;
            tickets--;
            pthread_mutex_unlock(&mymutex);
        }
        else
        {
            pthread_mutex_unlock(&mymutex);
            cout << "failed ticket:" << tickets << endl;
            break;
        }
    }
}

int main()
{
    pthread_mutex_init(&mymutex,nullptr);
    pthread_t tid1, tid2, tid3, tid4;
    // 创建线程
    pthread_create(&tid1, nullptr, function, (void *)"thread1");
    pthread_create(&tid2, nullptr, function, (void *)"thread2");
    pthread_create(&tid3, nullptr, function, (void *)"thread3");
    pthread_create(&tid4, nullptr, function, (void *)"thread4");
    // 主线程
    cout << tickets << endl;
    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);
    pthread_join(tid4, nullptr);
    pthread_mutex_destroy(&mymutex);
    return 0;
}
